<template>
  <el-card class="box-card">

    <!--  分配角色弹出框  -->
    <el-dialog title="分配角色"
               :visible.sync="dialogRole"
               width="50%"
               :before-close="handleCloseRole">

      <!--   角色筛选   -->
      <el-form :inline="true" style="height: 40px">
        <el-form-item>
          <my-select v-model="condition.statusRole"
                     placeholder="请选择状态"
                     :showList="condition.statusRoleList"
                     labelName='label'
                     valueName='value'/>
        </el-form-item>

        <el-form-item>
          <el-input
              clearable
              v-model="condition.keywordsRole"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入角色关键字"
              style="width:200px"
              @keyup.enter.native="searchRoles"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem" @click="searchRoles">
            搜索
          </el-button>
        </el-form-item>
      </el-form>

      <!--   角色选择   -->
      <el-form :model="roleForm">
        <el-tree
            :data="roleTreeData"
            show-checkbox
            ref="roleTree"
            node-key="id"
            :check-strictly=true
            :props="defaultProps"
            @check-change="handleCheckChange"
        >
        </el-tree>

        <!--  分页  -->
        <pagination
            :total="totalRole"
            :page_index="pageNumRole"
            @pageChange="pageChangeRole"
        />

        <el-form-item>
          <div class="sub-but">
            <el-button @click="dialogRole = false">取 消</el-button>
            <el-button type="primary" @click="submitRoleFormHandle('roleFrom')">确 定</el-button>
          </div>
        </el-form-item>
      </el-form>

    </el-dialog>


    <!--  新增/修改弹出框  -->
    <el-dialog
        :title="dialogTitle+'用户'"
        :visible.sync="dialogAddOrUpdate"
        width="40%"
        :before-close="handleCloseAdd">
      <el-form :model="userForm" :rules="userFormRules" ref="userForm" label-width="100px">

        <el-form-item label="头像" prop="headPortrait">
          <my-upload-img ref="upload"
                          @file-selected="handleFileSelected"
                          @image-removed="handleImageRemoved"
                          :imageUrl="userForm.headPortrait"
          />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isDisabled"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="isEnable">
          <el-radio-group v-model="userForm.isEnable">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>启用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="禁用原因" prop="disabledReason">
          <el-input v-model="userForm.disabledReason"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAddOrUpdateForm('userForm')">立即{{ dialogTitle }}</el-button>
          <el-button @click="resetForm('userForm')">重置</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>


    <!--  表格操作  -->
    <div class="select-div">
      <el-form :inline="true" style="height: 40px">
        <el-form-item>
          <my-select v-model="condition.isEnable"
                     placeholder="请选择状态"
                     :showList="condition.isEnableList"
                     labelName='label'
                     valueName='value'/>
        </el-form-item>

        <el-form-item>
          <el-input
              clearable
              v-model="condition.keywords"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入用户关键字"
              style="width:200px"
              @keyup.enter.native="searchUsers"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem" @click="searchUsers">
            搜索
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogAdd">新增</el-button>
        </el-form-item>


        <el-form-item>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
                     :disabled="this.selection.length === 0">删除选中
          </el-button>
        </el-form-item>

      </el-form>
    </div>


    <!--  表格内容  -->
    <el-table ref="multipleTable"
              :data="tableData"
              border
              highlight-current-row
              :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="headPortrait" label="头像" width="150">
        <template slot-scope="scope">
          <img style="width: 100%" :src="scope.row.headPortrait"/>
        </template>
      </el-table-column>

      <el-table-column prop="username" label="用户名"></el-table-column>

      <el-table-column prop="email" label="邮箱"></el-table-column>

      <el-table-column prop="roleVOList" label="角色" width="200">
        <template slot-scope="scope">
          <el-tag v-for="item of scope.row.roleVOList"
                  :key="item.id"
                  style="margin-right:0.2rem;margin-top:0.2rem">
            {{ item.name }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="isEnable" label="状态" sortable>
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.isEnable"
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
              @change="changeIsEnable(scope.row.id, scope.row.username,scope.row.isEnable)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column prop="disabledReason" label="禁用原因"></el-table-column>

      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="修改" placement="top-start">
            <el-button circle icon="el-icon-edit" size="mini" @click="dialogUpdate(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="分配角色" placement="top-start">
            <el-button circle icon="el-icon-s-operation" size="mini" @click="roleEdit(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="删除" placement="top-start">
            <el-button circle icon="el-icon-delete" size="mini" placement="top-start" type="danger"
                       @click="deleteCheck(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>

    </el-table>


    <!--  分页  -->
    <pagination
        :total="total"
        :page_index="pageNum"
        @pageChange="pageChange"
    />

  </el-card>
</template>

<script>
import { userApi, roleApi } from '@/api';

export default {
  data() {
    return {
      tableData: [],
      roleTreeData: [],
      selection: [],
      selectedNum: 0,
      userForm: {},
      roleForm: {},
      total: 0,
      pageNum: 1,
      pageSize: 10,
      totalRole: 0,
      pageNumRole: 1,
      pageSizeRole: 10,
      dialogAddOrUpdate: false,
      dialogRole: false,
      dialogTitle: '',
      isDisabled: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      condition: {
        keywords: null,
        isEnable: null,
        isEnableList: [
          {
            value: 0,
            label: "禁用"
          },
          {
            value: 1,
            label: "启用"
          }
        ],
        keywordsRole: null,
        statusRole: null,
        statusRoleList: [
          {
            value: 0,
            label: "禁用"
          },
          {
            value: 1,
            label: "启用"
          }
        ]
      },
      userFormRules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入用户密码', trigger: 'blur'}
        ],
      },
      selectedNodes: [], // 存储已选择的节点id
      selectedFile: null,
    }
  },


  methods: {
        /**
     * 处理文件选择
     */
    handleFileSelected(file) {
      this.selectedFile = file;
    },

    /**
     * 处理图片移除
     */
    handleImageRemoved() {
      this.selectedFile = null;
      this.userForm.headPortrait = '';
    },

    /**
     * 复选框事件
     * @param selection 选中数据数组
     */
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item.id)
      this.selectedNum = selection.length
    },

    /**
     * 搜索框事件
     */
    searchUsers() {
      this.pageNum = 1;
      this.loadUserList();
    },

    /**
     * 用户分页回调函数
     * @param val
     */
    pageChange(val) {
      this.pageNum = val.pageNum;
      this.pageSize = val.pageSize;
      this.loadUserList();
    },

    /**
     * 角色搜索框事件
     */
    searchRoles() {
      this.pageNumRole = 1;
      this.loadRoleList();
    },

    /**
     * 获取图片上传后的地址
     * @param data
     */
    handleUploadSuccess(data) {
      console.log(data)
      console.log(this.userForm.headPortrait)
      this.userForm.headPortrait = data.data;
      console.log(this.userForm.headPortrait)
    },

    /**
     * 角色树改变时的触发事件
     */
    handleCheckChange() {
      let checkedKey = this.$refs.roleTree.getCheckedKeys();
      console.log("分页数据改变前this.selectedNodes:", this.selectedNodes)
      console.log("分页数据改变前checkedKey:", checkedKey)
      if (checkedKey.length !== 0) {
        // 将已选择的节点id加入到selectedNodes
        this.selectedNodes = [...checkedKey];
      }
      // 去重
      this.selectedNodes = Array.from(new Set(this.selectedNodes));

      console.log("树数据改变:", this.selectedNodes)
    },

    /**
     * 角色分页回调函数
     * @param val
     */
    pageChangeRole(val) {
      // this.handleCheckChange();

      // 变更翻页数据
      this.pageNumRole = val.pageNum;
      this.pageSizeRole = val.pageSize;
      this.loadRoleList();

      // 在下一次DOM更新完成后重新设置已选择的节点为选中状态
      this.$nextTick(() => {
        console.log("分页数据改变后this.selectedNodes:", this.selectedNodes)
        console.log("分页数据改变后checkedKey:", this.$refs.roleTree.getCheckedKeys())
        this.$refs.roleTree.setCheckedKeys(this.selectedNodes);
        console.log("重新选中的节点:", this.$refs.roleTree.getCheckedKeys())
      });
    },

    /**
     * 当用户通过点击关闭图标或遮罩关闭 Dialog 时起效的事件
     */
    handleCloseAdd() {
      //关闭Dialog时清空表单
      this.$refs.userForm.resetFields();
      this.userForm = {};
      this.dialogAddOrUpdate = false;
    },
    handleCloseRole() {
      this.selectedNodes = [];
      this.totalRole = 0;
      this.pageNumRole = 1;
      this.pageSizeRole = 10;
      this.dialogRole = false;
    },


    // 重置弹出框内容
    resetForm(formName) {
      // 保存cover值用于释放URL
      const coverUrl = this.userForm.headPortrait;
      
      // 重置表单
      this.$refs[formName].resetFields();
      this.userForm = {};
      this.selectedFile = null;
      
      // 释放预览URL
      if (coverUrl && coverUrl.startsWith('blob:')) {
        URL.revokeObjectURL(coverUrl);
      }
      
      // 重置上传组件
      if (this.$refs.upload) {
        this.$refs.upload.clearSelection();
      }
    },

    /**
     * 新增按钮触发事件
     */
    dialogAdd() {
      this.dialogTitle = "新增";
      this.isDisabled = false;
      this.dialogAddOrUpdate = true;
    },


    /**
     * 启用/禁用用户
     */
    changeIsEnable(id, username, isEnable) {
      this.userForm.id = id;
      this.userForm.username = username;
      this.userForm.isEnable = isEnable;
      userApi.updateUser(this.userForm).then((response) => {
        if (response.data.code === 20000) {
          this.$message.success("修改成功！")
          this.loadUserList();
        }
      })
    },


    /**
     * 修改按钮触发事件
     * @param id 数据id
     */
    dialogUpdate(id) {
      this.isDisabled = true;
      userApi.getUserInfo(id).then((response) => {
        if (response.data.code === 20000) {
          //将当前行角色信息数据回显到弹出表单中，并打开表单
          this.userForm = response.data.data;
          this.userForm.password = '******';
          this.dialogTitle = "修改";
          this.dialogAddOrUpdate = true;
        }
      })
    },


    /**
     * 分配角色按钮事件
     * @param id 数据id
     */
    roleEdit(id) {
      userApi.getUserRoleIds(id).then(response => {
        if (response.data.code === 20000) {
          //将当前用户对应的角色回显到弹出框(获取与用户相关联的角色id)
          let roleIds = response.data.data;
          this.dialogRole = true;
          this.$nextTick(() => {
            this.$refs.roleTree.setCheckedKeys(roleIds);
            this.selectedNodes = roleIds
          });
          this.userForm.id = id;
        }
      })
    },


    /**
     * 分页查询角色列表
     */
    loadRoleList() {
      const params = {
        pageNum: this.pageNumRole,
        pageSize: this.pageSizeRole,
        status: this.condition.statusRole,
        keywords: this.condition.keywordsRole
      };
      
      roleApi.getRoleList(params).then((response) => {
        if (response.data.code === 20000) {
          if (response.data.data != null) {
            this.roleTreeData = response.data.data.pagingList;
            this.totalRole = response.data.data.count;
            return;
          }
          this.roleTreeData = null;
          this.totalRole = null;
        }
      })
    },


    /**
     * 提交角色分配表单
     *  @param formName 表单数据
     */
    submitRoleFormHandle(formName) {
      //获取tree中被选中节点的key所组成的数组
      const roleIds = this.$refs.roleTree.getCheckedKeys();
      console.log("选中角色id为：", roleIds);

      let userId = this.userForm.id;
      console.log("选中的userId：", userId);

      userApi.assignRoleToUser(userId, roleIds).then(response => {
        if (response.data.code === 20000) {
          this.$message({
            showClose: true,
            message: '操作成功!',
            type: 'success',
            onClose: () => {
              this.loadUserList()
            }
          });
        }
        this.dialogRole = false;
        this.resetForm(formName);
      })
    },


    /**
     * 删除数据
     * @param id 数据id
     */
    deleteCheck(id) {
      this.$confirm("删除后不可恢复", "提示", {
        type: "warning"
      }).then(() => {
        const ids = id == null ? this.selection : [id];
        userApi.deleteUsers(ids).then((response) => {
          if (response.data.code === 20000) {
            this.$message.success("用户删除成功！")
          }
          this.loadUserList();
        });
      })
    },


    /**
     * 查询用户列表
     */
    loadUserList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        isEnable: this.condition.isEnable,
        keywords: this.condition.keywords
      };
      
      userApi.getUserList(params).then((response) => {
        if (response.data.code === 20000) {
          if (response.data.data != null) {
            this.tableData = response.data.data.pagingList;
            this.total = response.data.data.count;
            return;
          }
          this.tableData = null;
          this.total = null;
        }
      })
    },


    /**
     * 提交新增表单
     * @param forName
     */
    submitAddOrUpdateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let formData = new FormData();
          formData.append('id', this.userForm.id);
          formData.append('username', this.userForm.username);
          formData.append('email', this.userForm.email);
          formData.append('isEnable', this.userForm.isEnable);
          formData.append('disabledReason', this.userForm.disabledReason);
          formData.append('password', this.userForm.password);
          if (this.selectedFile) {
            formData.append('headPortraitFile', this.selectedFile);
          }
          const apiMethod = this.userForm.id ? userApi.updateUser : userApi.addUser;
          apiMethod(formData).then((response) => {
            if (response.data.code === 20000) {
              this.$message({
                showClose: true,
                message: '操作成功！',
                type: 'success',
                onClose: () => {
                  this.loadUserList()
                    this.dialogAddOrUpdate = false;
                    this.resetForm(formName);
                }
              });
            }
          })
        } else {
          this.$message.error('请完整填写表单!');
          return false;
        }
      })
    },

  },


  created() {
    this.loadUserList();
    this.loadRoleList();
  }

}
</script>

<style scoped>
.sub-but {
  margin: 20px 150px 10px 150px;
}
</style>